//
//  GTMultithreadController.m
//  semple-code-oc
//
//  Created by zhaoguoteng on 2022/1/5.
//

#import "GTMultithreadController.h"

@interface GTMultithreadController ()

@property (nonatomic, strong) dispatch_queue_t queue;

@end

@implementation GTMultithreadController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT);
    
    [self delayTest:^(id res) {
        DDLogDebug(@"######## res = %@", res);
    }];
    
    DDLogDebug(@"###");
}

- (void)delayTest:(void(^)(id res))complete {
    
    dispatch_async(self.queue, ^{
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        
        __block int n = 0;
        {
            [self delayTest01:^(int a){
                n = a;
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
        
        __block int m = 0;
        {
            [self delayTest02:n complete:^(int b) {
                m = b;
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
        
        if (complete) {
            complete(@(m));
        }
    });
}

- (void)delayTest01:(void(^)(int a))complete {
    
    dispatch_async(self.queue, ^{
        sleep(1.0);
        if (complete) {
            DDLogDebug(@"###### delayTest01");
            complete(100);
        }
    });
}

- (void)delayTest02:(int)a complete:(void(^)(int b))complete {
    dispatch_async(self.queue, ^{
        sleep(1.0);
        if (complete) {
            DDLogDebug(@"###### delayTest02");
            complete(a * 2);
        }
    });
}

@end
